<template>
  <div>
    <a-space size="middle">
      <a-tag :disabled="disabled" v-for="(item, index) of dataList" :key="item.materialId" :closable="!disabled" @close="remove(item, index)"
        >{{ item.materialName }} - {{ item.count }}</a-tag
      >
      <a-button @click="openPick" :disabled="disabled">添加</a-button>
    </a-space>

    <!-- 查询窗口 -->
    <a-modal
      destroyOnClose
      :width="modalWidth"
      :visible="visible"
      title="选择"
      @ok="handleSelected"
      @cancel="close"
      style="top:50px"
      cancelText="关闭"
    >
      <a-form style="margin-bottom:20px;" layout="inline" @keyup.enter.native="search">
        <a-row :gutter="48">
          <a-col :md="8" :sm="24">
            <a-form-item>
              <a-input v-model="queryParam.name" placeholder="场地物资名称" />
            </a-form-item>
          </a-col>

          <a-col :md="8" :sm="24">
            <a-form-item>
              <a-input v-model="queryParam.code" placeholder="场地物资编码" />
            </a-form-item>
          </a-col>
          <a-col :md="8" :sm="24">
            <a-button type="primary" @click="onSearch">查询</a-button>
          </a-col>
        </a-row>
      </a-form>
      <a-card :loading="loading">
        <a-table
          ref="table"
          size="middle"
          rowKey="id"
          :columns="columns"
          :dataSource="dataSource"
          :pagination="ipagination"
          :rowSelection="{ selectedRowKeys: selectedRowKeys, onChange: onSelectChange, type: 'radio' }"
          :loading="loading"
          @change="handleTableChange"
        >
        </a-table>
      </a-card>
    </a-modal>

    <!-- 设置数量 -->
    <a-modal title="输入申请数量" :visible="countVisible" @ok="handleOk" @cancel="countVisible = false">
      <a-input v-model="count" placeholder="请输入数量" type="number"></a-input>
    </a-modal>
  </div>
</template>

<script>
import { filterObj } from '@/utils/util'
import { postAction, getAction } from '@/api/manage'
import { JeecgListMixin } from '@/mixins/JeecgListMixin'
import { find } from 'lodash'

export default {
  name: 'MaterialPick',
  props: {
    value: [String, Array],
    disabled: Boolean,
    searchType: {
      type: String,
      default() {
        return ''
      }
    },
    searchIcon: Boolean,
    searchBtnText: String
  },
  mixins: [JeecgListMixin],
  data() {
    return {
      loading: false,
      visible: false,
      countVisible: false,
      modalWidth: 1000,
      labelCol: {
        xs: { span: 24 },
        sm: { span: 5 }
      },
      wrapperCol: {
        xs: { span: 24 },
        sm: { span: 16 }
      },
      url: '/material/list',
      names: '',
      departTree: [],
      queryParam: {
        type: this.searchType
      },
      count: '',
      dataList: [],
      dataSource: [],
      checkedKeys: [],
      iExpandedKeys: [],
      selectedRowKeys: [],
      selectUserRows: [],
      selectUserIds: [],
      title: '用户',
      columns: [
        {
          title: '类型',
          align: 'center',
          dataIndex: 'type_dictText',
          width: 150
        },
        {
          title: '名称',
          align: 'center',
          dataIndex: 'name',
          width: 200
        },
        {
          title: '编码',
          align: 'center',
          dataIndex: 'code',
          width: 150
        },
        {
          title: '数量',
          align: 'center',
          dataIndex: 'count',
          width: 100
        },
        {
          title: '状态',
          align: 'center',
          dataIndex: 'status_dictText',
          width: 120
        }
      ],
      ipagination: {
        current: 1,
        pageSize: 10,
        pageSizeOptions: ['10', '20', '30'],
        showTotal: (total, range) => {
          return range[0] + '-' + range[1] + ' 共' + total + '条'
        },
        showQuickJumper: true,
        showSizeChanger: true,
        total: 0
      },
      isorter: {
        column: 'createTime',
        order: 'desc'
      }
    }
  },
  watch: {
    value(nv, ov) {
      this.dataList = Object.assign([],nv)
      if (nv) {
        this.onSearch()
      } else {
        this.dataSource = []
      }
    },
    searchType(nv, ov) {
      this.queryParam = Object.assign({}, this.queryParam, {
        type: nv
      })
      if (nv && nv != ov) {
        this.clear()
      }
    }
  },
  methods: {
    remove(data, index) {
      this.dataList.splice(index, 1)
    },
    openPick() {
      this.visible = true
      this.clear()
      this.onSearch()
    },
    clear() {
      this.queryParam = {
        type: this.searchType
      }
      this.dataSource = []
      this.selectedRowKeys = []
      this.selectUserRows= []
      this.selectUserIds= []
    },
    handleOk() {
      if (!this.count) return this.$message.warning('请输入大于零的数量！')
      if (Array.isArray(this.selectionRows) && this.selectionRows.length) {
        let data = Object.assign({}, this.selectionRows[0])
        if (this.count > data.count) return this.$message.warning('超出可申请数量！')
        if (find(this.dataList, { materialId: data.id }))
          return this.$message.warning('该物品已经存在列表中，如需修改请移除后操作！')
        data.count = this.count
        this.dataList.push({
          applyId: '',
          count: data.count,
          id: '',
          materialId: data.id,
          materialName: data.name,
          materialType: data.type
        })
      }
      this.$emit('input', this.dataList)
      this.$emit('change', this.dataList)
      this.count = ''
      this.countVisible = false
      this.visible = false
    },
    handleSelected() {
      if (this.selectionRows.length) {
        this.count = ''
        this.countVisible = true
      } else {
        this.$message.warning('请选择一条数据！')
      }
    },
    close() {
      this.visible = false
      this.countVisible = false
    },
    getQueryParams() {
      let param = Object.assign({status:1,usable:true}, this.queryParam, this.isorter)
      param.field = this.getQueryField()
      param.pageNo = this.ipagination.current
      param.pageSize = this.ipagination.pageSize
      return filterObj(param)
    },
    onCheck(checkedKeys, info) {
      this.hiding = false
      //this.checkedKeys = checkedKeys.checked
      // <!---- author:os_chengtgen -- date:20190827 --  for:切换父子勾选模式 =======------>
      if (this.checkStrictly) {
        this.checkedKeys = checkedKeys.checked
      } else {
        this.checkedKeys = checkedKeys
      }
      // <!---- author:os_chengtgen -- date:20190827 --  for:切换父子勾选模式 =======------>
    },
    setThisExpandedKeys(node) {
      if (node.children && node.children.length > 0) {
        this.iExpandedKeys.push(node.key)
        for (let a = 0; a < node.children.length; a++) {
          this.setThisExpandedKeys(node.children[a])
        }
      }
    },
    onSelectChange(selectedRowKeys, selectionRows) {
      this.selectedRowKeys = selectedRowKeys
      this.selectionRows = selectionRows
    },
    onSearch() {
      this.loadData(1)
    },
    async loadData(arg) {
      if (arg === 1) {
        this.ipagination.current = 1
      }
      this.dataSource = []
      this.loading = true
      let params = this.getQueryParams() //查询条件
      await getAction(this.url, params)
        .then(res => {
          if (res.success) {
            this.dataSource = res.result.records
            this.ipagination.total = res.result.total
          }
        })
        .finally(() => {
          this.loading = false
        })
    },
    handleTableChange(pagination, filters, sorter) {
      //TODO 筛选
      if (Object.keys(sorter).length > 0) {
        this.isorter.column = sorter.field
        this.isorter.order = 'ascend' === sorter.order ? 'asc' : 'desc'
      }
      this.ipagination = pagination
      this.loadData()
    }
  }
}
</script>

<style scoped></style>
